<template>
  <div>
    <breadcrumb title="教师管理" homePath="/admin" />
    <el-card>
      <!-- 头部搜索 -->
      <el-row class="search">
        <!-- 关键词 -->
        <el-select v-model="charType" placeholder="请选择">
          <el-option
            v-for="item in charTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 搜索内容 -->
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="inputText"
        >
        </el-input>
        <!-- 搜索和重置 -->
        <el-button type="primary" @click="gotoSearch">搜索</el-button>
        <el-button type="primary" @click="resetDate">重置</el-button>
        <el-button type="primary" @click="newUserInfoDialogVisible = true"
          >添加教师</el-button
        >
      </el-row>

      <!-- 用户信息 -->
      <el-table :data="teacherData" stripe style="width: 100%" border>
        <template slot="empty">
          <p>{{ baseInfoText }}</p>
        </template>
        <el-table-column prop="id" label="工号"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="sex" label="性别"> </el-table-column>
        <el-table-column prop="address" label="生源地"> </el-table-column>
        <el-table-column prop="classes" label="管理班级"> </el-table-column>
        <el-table-column label="类型">教师 </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部分页栏 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="allTeacherNum"
      >
      </el-pagination>

      <!-- 编辑用户对话框 -->
      <el-dialog
        title="教师信息"
        :visible.sync="userInfoDialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <!-- 用户信息表单 -->
        <el-form
          :model="userInfoForm"
          :rules="userInfoRules"
          ref="userInfoRef"
          label-width="100px"
        >
          <el-form-item label="工号" prop="id">
            <el-input
              v-model.number="userInfoForm.id"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="username">
            <el-input
              v-model.number="userInfoForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model.number="userInfoForm.password"
              autocomplete="off"
            ></el-input
          ></el-form-item>
          <el-form-item label="生源地" prop="address">
            <el-input
              v-model.number="userInfoForm.address"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="userInfoForm.sex" label="男" border>男</el-radio>
            <el-radio v-model="userInfoForm.sex" label="女" border>女</el-radio>
            <!-- <el-input
              v-model.number="userInfoForm.sex"
              autocomplete="off"
            ></el-input> -->
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-radio v-model="userInfoForm.type" label="1" border
              >管理员</el-radio
            >
            <el-radio v-model="userInfoForm.type" label="2" border
              >学生</el-radio
            >
            <el-radio v-model="userInfoForm.type" label="3" border
              >老师</el-radio
            >
            <!-- <el-input
              v-model.number="userInfoForm.type"
              autocomplete="off"
            ></el-input> -->
          </el-form-item>
        </el-form>
        <!-- 关闭和提交对话框 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="userInfoDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="comfirmUpdate">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="教师信息"
        :visible.sync="newUserInfoDialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <!-- 用户信息表单 -->
        <el-form
          :model="newUserInfoForm"
          :rules="newUserInfoRules"
          ref="newUserInfoRef"
          label-width="100px"
        >
          <el-form-item label="工号" prop="id">
            <el-input
              v-model.number="newUserInfoForm.id"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="username">
            <el-input
              v-model.number="newUserInfoForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model.number="newUserInfoForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-input
              v-model.number="newUserInfoForm.sex"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="生源地" prop="address">
            <el-input
              v-model.number="newUserInfoForm.address"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="管理班级" prop="classes">
            <el-input
              v-model.number="newUserInfoForm.classes"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- 关闭和提交对话框 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="newUserInfoDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="comfirmAdd">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import Breadcrumb from "components/Breadcrumb.vue";

import { getUsersByTypePage } from "network/users/getUsersByTypePage";
import { getUsersByTypeAndChar } from "network/users/getUsersByTypeAndChar";
import { delUserdata } from "network/users/delUserdata";
import { upUserdata } from "network/users/upUserdata";
import { addUserdata } from "network/users/addUserdata";
export default {
  data() {
    return {
      teacherData: [],
      allTeacherNum: 0,
      currentPage: 1,
      queryInfo: {
        pagenum: 1,
        pagesize: 2,
      },
      charTypeList: [
        { value: "username", label: "姓名" },
        { value: "address", label: "地址" },
        { value: "id", label: "工号" },
        { value: "classes", label: "管理班级" },
      ],
      charType: "",
      inputText: "",
      userInfoDialogVisible: false,
      userInfoForm: {
        id: undefined,
        username: "",
        password: "",
        sex: "",
        address: "",
        type: "",
      },
      userInfoRules: {
        id: [
          { required: true, message: "请输入用户ID", trigger: "blur" },
          { type: "number", message: "Id必须为数字值" },
        ],
        username: [
          { required: true, message: "请输入用户姓名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        sex: [{ required: true, message: "请输入用户性别", trigger: "blur" }],
        address: [
          { required: true, message: "请输入用户地址", trigger: "blur" },
        ],
        type: [{ required: true, message: "请输入用户类型", trigger: "blur" }],
      },
      newUserInfoDialogVisible: false,
      newUserInfoForm: {
        id: undefined,
        username: "",
        sex: "",
        address: "",
        type: 3,
        password: "",
        classes: "",
      },
      newUserInfoRules: {
        id: [
          { required: true, message: "请输入用户ID", trigger: "blur" },
          { type: "number", message: "Id必须为数字值" },
        ],
        username: [
          { required: true, message: "请输入用户姓名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        sex: [{ required: true, message: "请输入用户性别", trigger: "blur" }],
        address: [
          { required: true, message: "请输入用户地址", trigger: "blur" },
        ],
        classes: [
          { required: true, message: "请输入用户管理班级", trigger: "blur" },
        ],
      },
      baseInfoText: "",
    };
  },
  components: {
    Breadcrumb,
  },
  async created() {
    this.getUsersByTypePage();
    this.$store.commit("setCurrentIndex", {
      type: "adminCurrentIndex",
      index: 1,
    });
  },
  methods: {
    // 获取所有教师信息
    async getUsersByTypePage() {
      let res = await getUsersByTypePage(
        3,
        this.queryInfo.pagesize,
        this.queryInfo.pagenum
      );

      this.teacherData = res.data;
      this.allTeacherNum = res.total;
      this.$message.success("获取教师列表成功");

      if (this.allTeacherNum == 0) {
        this.baseInfoText = "暂无数据";
      }
    },
    // 处理改变一页的数量
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      if (this.inputText == "") {
        this.getUsersByTypePage();
      } else {
        this.getUsersByTypeAndChar();
      }
    },
    // 处理改变页码
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      if (this.inputText == "") {
        this.getUsersByTypePage();
      } else {
        this.getUsersByTypeAndChar();
      }
    },
    // 搜索处理
    gotoSearch() {
      if (this.inputText == "" || this.charType == "") {
        return this.$message.error("请输入关键字再查询");
      }
      this.queryInfo.pagenum = 1;
      this.queryInfo.pagesize = 2;
      this.getUsersByTypeAndChar();
    },
    // 根据关键字找用户
    async getUsersByTypeAndChar() {
      let res = await getUsersByTypeAndChar(
        3,
        this.inputText,
        this.charType,
        this.queryInfo.pagesize,
        this.queryInfo.pagenum
      );
      console.log(res);
      this.teacherData = res.data;
      this.allTeacherNum = res.total;
      this.$message.success("获取教师列表成功");
    },
    // 重置用户列表
    resetDate() {
      (this.inputText = ""), (this.charType = "");
      this.getUsersByTypePage();
    },
    // 展示表单及处理
    showEditDialog(userInfo) {
      this.userInfoDialogVisible = true;
      for (let k in this.userInfoForm) {
        this.userInfoForm[k] = userInfo[k];
      }
      this.userInfoForm.type += "";
    },
    //对话框外关闭表单确认弹窗
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 更新用户信息
    async comfirmUpdate() {
      console.log(this.$refs.userInfoRef);
      this.$refs.userInfoRef.validate(async (valid) => {
        if (!valid) return;
        let { userInfoForm } = this;
        userInfoForm.u_id = userInfoForm.id;
        userInfoForm.type -= 0;
        if (userInfoForm.username == "zrf") {
          return this.$message.error("这是超级管理员~~不允许删除！！");
        }
        let res = await upUserdata(userInfoForm);
        await this.getUsersByTypePage();
        this.$message.success(res);
        this.userInfoDialogVisible = false;
      });
    },
    // 删除用户
    async removeUserById(id) {
      // 弹框询问是否删除数据 取消的话必须用catch捕捉
      // 成功返回confirm 失败返回cancel
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("已经取消了删除");
      }
      const res = await delUserdata(id);
      console.log(res);
      this.$message.success("删除教师成功");
      this.queryInfo.pagesize = 2;
      this.queryInfo.pagenum = 1;
      this.getUsersByTypePage();
    },
    // 添加用户
    async comfirmAdd() {
      this.$refs.newUserInfoRef.validate(async (valid) => {
        if (!valid) return;
        const res = await addUserdata(this.newUserInfoForm);
        if (res == "添加用户成功") this.$message.success("添加教师成功");
        else this.$message.info(res);
        this.getUsersByTypePage();
        (this.newUserInfoForm = {
          id: undefined,
          username: "",
          sex: "",
          address: "",
          type: 3,
          password: "",
          classes: "",
        }),
          (this.newUserInfoDialogVisible = false);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  padding: 10px 10px;
  .search {
    display: flex;
    .el-select {
      width: 150px;
    }
    .el-input {
      width: 200px;
      margin: 0 20px;
    }
    .el-button:last-child {
      position: absolute;
      right: 0;
    }
  }
  .el-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>